from django.db.models import Sum
from django.shortcuts import render
from rest_framework import viewsets
from .models import Player, Team
from rest_framework.decorators import action
from django.http import JsonResponse
from .serializers import PlayerSerializers
from spider import Spider


class PlayerViewSet(viewsets.ModelViewSet):
    queryset = Player.objects
    serializer_class = PlayerSerializers

    @action(methods=['get'], detail=False)
    def index(self, request, *args, **kwargs):

        serializer = self.get_serializer(
            data=self.request.query_params, include_fields=['season'])
        serializer.is_valid(raise_exception=True)
        season = serializer.data.get('season')

        visual_season = self.visual_season(season)

        top5 = self.top5(season)

        team_score_list = []
        for key in ['points', 'games', 'mins','fgpct','tpm','tppct','ftpct']:
            team_score = self.team_score(season, key)
            team_score_list.append(team_score)

        visual_team = self.visual_team()

        return render(request, 'index.html', context=locals())

    @action(methods=['get', ], detail=False)
    def spider(self, request, *args, **kwargs):
        """爬取数据"""
        # 赛季
        for season in range(1996, 2024):
            for page in range(1, 12):
                url = f'https://api.nba.cn/sib/v2/league/playerstats?os_version=10.0.0&app_version=1.1.0&channel=nba-server&t=1712584763&season={
                    season}&seasonType=2&position=All&individual=All&conference=All&total=perGame&page_size=50&page_no={page}'
                res_list = Spider(url=url).run()
                item_list = []
                for res in res_list:
                    # 季度
                    season = res['Season']

                    # 球员
                    player = res['player']

                    # player id
                    player_id = res['player_id']

                    # 球队
                    team = res['team']
                    team = Team.get_or_create(team)

                    # 比赛场次
                    games = res['Games']

                    # 出场时间
                    mins = res['Minspg']

                    # 得分
                    points = res['Pointspg']

                    # 篮板
                    rebs = res['Rebs']

                    # 助攻
                    assists = res['Assists']

                    # 抢断
                    steals = res['Steals']

                    # 盖帽
                    blocks = res['Blocks']

                    # 投篮命中率
                    fgpct = res['Fgpct']

                    # 三分命中数
                    tpm = res['Tpm']

                    # 三分命中率
                    tppct = res['Tppct']

                    # 罚球命中率
                    ftpct = res['Ftpct']

                    item = {
                        'season': season,
                        'name': player,
                        'player_id': player_id,
                        'team': team,
                        'games': games,
                        'mins': mins,
                        'points': points,
                        'rebs': rebs,
                        'assists': assists,
                        'steals': steals,
                        'blocks': blocks,
                        'fgpct': fgpct,
                        'tpm': tpm,
                        'tppct': tppct,
                        'ftpct': ftpct,
                    }
                    item_list.append(Player(**item))

                Player.objects.bulk_create(item_list)
                print(f'第{season}季度第{page}页爬取完成!')

        return JsonResponse(data={'msg': '爬取成功！'})

    def visual_season(self, season):
        """# 赛季
            # 球员的总数
            # 球员总出场时间
            # 球员总得分
            # 人均得分
            # 平均得分
        """
        players = self.get_queryset().filter(season=season)
        nums = len(players)
        mins = players.aggregate(mins=Sum('mins'))['mins']
        points = players.aggregate(points=Sum('points'))['points']
        per_player_points = round(points / nums, 2)
        per_min_points = round(points / mins, 2)
        data = {
            'nums': nums,
            'mins': mins,
            'points': points,
            'per_player_points': per_player_points,
            'per_min_points': per_min_points,
        }
        return data

    def visual_team(self):
        """
        不同赛季下，每个球队不同数据的变化
        """
        teams = list(Team.objects.all().values_list('name', flat=True))
        seasons = list(self.get_queryset().values_list(
            'season', flat=True).distinct())
        seasons.sort()

        keys = [key for key in Player._meta.get_fields() if key.name not in [
            'id', 'season', 'name', 'player_id', 'team']]

        result = {}
        for key in keys:
            tmp_result = {}
            for season in seasons:
                res = self.team_score(season, key.name)['seriesData']
                max_val = max([item['value'] for item in res])
                sum_val = sum([item['value'] for item in res])
                tmp_result[season] = res
                tmp_result[f'{season}max'] = max_val
                tmp_result[f'{season}sum'] = sum_val
            result[key.help_text] = tmp_result

        data = {
            'seasons': seasons,
            'teams': teams,
            'result': result,
            'keys': [key.help_text for key in keys]
        }

        return data

    def top5(self, season):
        """
        排名前5的球员
        """
        players = list(
            self.get_queryset().filter(season=season).order_by('-points').values('name', 'points', 'mins', 'player_id')[
                :5])
        return players

    def team_score(self, season, key):
        """当前赛季下，每个球队的总得分"""

        players = self.get_queryset().filter(season=season)

        # 不同的球队
        teams = list(players.values_list('team__name', flat=True).distinct())

        res = []
        for team in teams:
            points = players.filter(team__name=team).aggregate(
                points=Sum(key))['points']
            res.append({
                'name': team,
                'value': points
            })

        text = getattr(Player, key).field.help_text
        season = f'{season}-{int(season) + 1}'
        data = {
            'legendData': teams,
            'seriesData': res,
            'text': text,
            'season': season
        }

        return data
